import {Component, OnInit, Input} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {HttpService} from '../../service/http.service';
import {User} from '../../module/user';
import {Cookie} from 'ng2-cookies/ng2-cookies';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.css']
})
export class HeaderComponent implements OnInit {
  @Input() bookKey: String;
  email: string;
  pwd: string;
  loginBoxStatus = false;
  nickname: string;

  constructor(private router: Router, private httpService: HttpService) {
  }

  ngOnInit() {
    this.nickname = Cookie.get('nickname');
  }

  search() {
    console.log(this.bookKey);
    this.bookKey = this.bookKey.trim();
    if (this.bookKey != null && this.bookKey.length !== 0) {
      this.router.navigate(['/search', this.bookKey]);
    }
  }

  loginBox() {
    this.loginBoxStatus = true;
  }

  hiddenLoginBox() {
    this.loginBoxStatus = false;
  }

  login() {
    this.httpService.userLogin(this.email, this.pwd).then(r => {
      if (r.code === 0) {
        console.log(r.data)
        this.nickname = r.data.nickname;
        Cookie.set('email', r.data.email);
        Cookie.set('headimgurl', r.data.headimgurl);
        Cookie.set('token', r.data.token);
        Cookie.set('id', '' + r.data.id);
        Cookie.set('nickname', r.data.nickname);
        Cookie.set('sex', '' + r.data.sex);
        Cookie.set('vipDeadline', r.data.vipDeadline);
        this.loginBoxStatus = false;
        this.email = null;
        this.pwd = null;
      } else {
        alert(r.msg);
      }
    });
  }

  logout() {
    Cookie.delete('email');
    Cookie.delete('token');
    Cookie.delete('id');
    Cookie.delete('nickname');
    Cookie.delete('sex');
    Cookie.delete('vipDeadline');
    this.nickname = null;
    this.router.navigate(['/']);
  }

  userInfo() {
    this.router.navigate(['personal']);
  }
}
